//
//  StatusPictureView.swift
//  SinaWeiBo20
//
//  Created by tarena on 16/3/25.
//  Copyright © 2016年 tarena. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

private let pictureCellID = "pictureCellID"
private let pictureCellMargin: CGFloat = 5

class StatusPictureView: UICollectionView {
    
    let itemWidth = (screenW - 2 * StatusCellMarigin - 2 * pictureCellMargin) / 3.0
    
    //MARK: 定义外部模型属性
    var imageURLs:[NSURL]? {
        didSet{
            //修改配图视图的大小
            let pSize = caclePictureViewSize()
            
            
            //更新配图视图的大小
            self.snp_makeConstraints { (make) -> Void in
                make.size.equalTo(pSize)
            }
            
            //修改测试的文案
//            testLabel.text = "\(imageURLs?.count ?? 0)"

            //刷新列表
            reloadData()
            
        }
    }
    
    //重写构造方法
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumInteritemSpacing = pictureCellMargin
        flowLayout.minimumLineSpacing = pictureCellMargin
        flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth)
        super.init(frame: CGRectZero, collectionViewLayout: flowLayout)
        
        self.registerClass(PictureCell.self, forCellWithReuseIdentifier: pictureCellID)
        self.dataSource = self
        self.delegate = self
        self.scrollsToTop = false
        backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //计算配图视图的大小
    private func caclePictureViewSize() -> CGSize {
        //计算配图的大小
        //1。获取配图的数量
        let imageCount = imageURLs?.count ?? 0
       
        
        //没有图片
        if imageCount == 0 {
            return CGSizeZero
        }
        //2.取出collectionView 的流水布局
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //单张图片
        if imageCount == 1 {
            //先给定固定尺寸
            var imageSize = CGSize(width: 120, height: 120)
            let key = imageURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            if image != nil {
                imageSize = image.size
            }
            //设置单张图片的 itemSize
            layout.itemSize = imageSize
            return imageSize
        }
        
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        if imageCount == 4 {
            //多张如果是4 会按照 2*2 显示
            let w = itemWidth * 2 + pictureCellMargin
            return CGSize(width: w, height: w)
        }
        
        let row = CGFloat((imageCount - 1) / 3 + 1)
        let w = itemWidth * 3 + pictureCellMargin * 2
        let h = itemWidth * row + (row - 1) * pictureCellMargin
        return CGSizeMake(w, h)
    }
    
}


//MARK : 数据源方法
extension StatusPictureView : UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//         print(__FUNCTION__)
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellID, forIndexPath: indexPath) as! PictureCell
        
        
        cell.imageURL = imageURLs![indexPath.row]
        return cell
    }
}


class PictureCell: UICollectionViewCell {
    //MARK: 定义外部模型属性
    var imageURL: NSURL? {
        didSet{
            iconView.sd_setImageWithURL(imageURL)
        }
    }
    
    //MARK: 重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 设置页面 和布局
    private func setupUI() {
        contentView.addSubview(iconView)
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(snp_edges)
        }
    }
    
    
    
    private lazy var iconView: UIImageView = {
       let iv = UIImageView()
        
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        
        //在纯代码 开发中  图片的默认是 剪裁  是没有开启的
        iv.clipsToBounds = true
        
        return iv
    }()
}





